package com.example.outdoor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ImportProductFile extends ListActivity{
	SQLiteDatabase db1 = null;
	private static String DBNAME = "OutdoorAppDB.db";
    private File currentDir;
    private FileArrayAdapter adapter;
    Button BrowseAFile;
	Button browserAvenueFile;
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        currentDir = new File("sdcard/");
		       fill(currentDir);
//		       onFileClick();
	       
	 }
	  private void fill(File f)
	    {
	        File[]dirs = f.listFiles();
	         this.setTitle("Current Dir: "+f.getName());
	         List<Option>dir = new ArrayList<Option>();
	         List<Option>fls = new ArrayList<Option>();
	         try{
	             for(File ff: dirs)
	             {
	                if(ff.isDirectory())
	                    dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
	                else
	                {
	                    fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
	                }
	             }
	         }catch(Exception e)
	         {
	             
	         }
	         Collections.sort(dir);
	         Collections.sort(fls);
	         dir.addAll(fls);
	         if(!f.getName().equalsIgnoreCase("sdcard"))
	             dir.add(0,new Option("..","Parent Directory",f.getParent()));
	         adapter = new FileArrayAdapter(ImportProductFile.this,R.layout.import_product,dir);
	         this.setListAdapter(adapter);
	    }
	    @Override
	    protected void onListItemClick(ListView l, View v, int position, long id) {
	        // TODO Auto-generated method stub
	        super.onListItemClick(l, v, position, id);
	        Option o = adapter.getItem(position);
	        if(o.getData().equalsIgnoreCase("folder")||o.getData().equalsIgnoreCase("parent directory")){
	                currentDir = new File(o.getPath());
	                fill(currentDir);
	        }
	        else
	        {
	          onFileClick(o);
	        }
	    }
	    
	    private void onFileClick(Option o)
	    {
	    	try{ 
	        //Toast.makeText(this, "File Clicked: "+o.getPath(), ToORT).show();
	    		
	    	  db1 = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	  
	          //Create Table
	    	  db1.execSQL("create table IF NOT EXISTS tblProduct (ID INTEGER PRIMARY KEY,ProductCode  VARCHAR,ProductName VARCHAR,VersionCode  VARCHAR,VersionName VARCHAR,CategoryCode VARCHAR,CategoryDescription VARCHAR);");
	       
//	         InputStream inputStream = getAssets().open("PROD_VER.TXT");
	        
	    	File myFile = new File(o.getPath());
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(
					new InputStreamReader(fIn));
			
			 String line; 
		        String [] rowData = null;
	    	       while ((line = myReader.readLine()) != null)
		        {
	    	    	 
			        	rowData = line.split(",");
			        	  if(!rowData[0].contains("#"))
			        	  {  
			        		  db1.execSQL("INSERT INTO tblProduct (ProductCode,ProductName,VersionCode,VersionName,CategoryCode,CategoryDescription) VALUES ('" + rowData[0].toString().replace("\"", "") + "','" + rowData[1].toString().replace("\"", "").replace("'", "&#39;") + "','" + rowData[2].toString().replace("\"", "") + "','" + rowData[3].toString().replace("\"", "").replace("'", "&#39;") + "','" + rowData[4].toString().replace("\"", "") + "','" + rowData[5].toString().replace("\"", "").replace("'", "&#39;") + "');");
			        	  }
			        
		        } 	
	    	      // db1.execSQL("INSERT INTO tblProduct (Obstruction)  VALUES ('ANGULO')('ARBOLES')('EDIFICIO')('GRAFITIS')('OTRO AVISO')('PARADA')('POSTE DE LUZ')('RAMA')('SEMAFORO')('TENDIDO ELECTRICO')('OTROS')('NINGUNA');");
	    	       Toast.makeText(getBaseContext(),
							"File uploaded successfully",
							Toast.LENGTH_SHORT).show();
	    	}
	    	
	        catch (Exception e) {
	            Log.e("HTTP", "Error in http connection " + e.toString());
	        }   
			    
	    }
	   
	

}
